import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { TypeOption } from './type-option.model';
import { LayerFormsService } from '../layer-forms.service';
import { StepTypes } from '../steps.model';

@Component({
  selector: 'ege-layer-forms-info',
  templateUrl: './layer-forms-info.component.html',
  styleUrls: ['./layer-forms-info.component.scss']
})
export class LayerFormsInfoComponent implements OnInit {

  forms: FormGroup;
  typeOptions: TypeOption[] = [
    { label: 'WFS', value: 'WFS' },
    { label: 'WMS', value: 'WMS' },
    { label: 'JSONXY', value: 'JSONXY' },
    { label: 'JSON', value: 'JSON' }
  ];

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private fb: FormBuilder,
    private layerFormsService: LayerFormsService
  ) { }

  ngOnInit() {
    const values = this.layerFormsService.forms || {};
    const { title, type } = values;
    this.forms = this.fb.group({
      title      : [ title || '', [ Validators.required ] ],
      type       : [ type || '', [ Validators.required ] ]
    });
  }

  submitForm(event: Event): void {
    for (const i in this.forms.controls) {
      this.forms.controls[ i ].markAsDirty();
    }
    if(this.forms.valid) {
      this.layerFormsService.addValues(this.forms.value);
      const step: StepTypes = this.layerFormsService.nextStep();
      this.router.navigate([`../${step}`], { relativeTo: this.activatedRoute });
    }
  }

  getFormControl(name) {
    return this.forms.controls[ name ];
  }

}
